'''
Created on Sep 29, 2011

@author: f13
'''
import random, time, Config, Logger, Device
from multiprocessing import Process

config = Config.config

class DeviceManager():
    def __init__(self):
        self.logger = Logger.logger.deviceMgtLogger
        self.logger.log(1, "Logger initialized successfully.")
        self.startTime = 0
        
    def buildInitializationID(self):
        numberAssigned = False
        while not numberAssigned:
            randomNumberString = hex(random.randint(1,config.rawPacketSize))
            randomNumber = randomNumberString[2:].upper()
            if (randomNumber not in config.currentDevices):
                config.currentDevices[randomNumber] = Device.Device()
                numberAssigned = True
        return randomNumber
    
    def initializeDevice(self, communicationManager, packet):
        ID = self.buildInitializationID()
        self.initializerProcess = Process(target=self.assignInitializationID, args=(communicationManager, ID, packet))
        self.initializerProcess.start()
        
    def assignInitializationID(self, communicationManager, ID, packet):
        self.startTime = time.clock()
        while True:
            packet.deviceID = ID
            packet.statusCode = "1000"
            communicationManager.sendPacket(packet)
            time.sleep(config.initializationDelay)
            
    def confirmDevice(self, packet):
        device = config.currentDevices[packet.deviceID]
        device.deviceType = packet.deviceType
        self.initializerProcess.terminate()
        config.packetSet.discard(device.deviceType + "0004000100000000000000000000\n")
        print "Total time for initialization:", (time.clock() - self.startTime), "seconds."
        config.currentDevices[packet.deviceID].confirmed = True
        self.logger.log(2, "New device initialized, ID: " + packet.deviceID)
        device.heartbeats = 1
        
    def checkSignature(self, packet):
        lightLockPattern = packet.data[12:] #trim 0's
        if str(lightLockPattern) in config.lightLockCodes:
            print "User: ", config.lightLockCodes[str(lightLockPattern)], " has unlocked with pattern: ", lightLockPattern
        else:
            print "Unkown code send to Helios!"
        config.packetSet.discard(packet.toString()) #remove this packet from the packet set to that we are ready to listen for new!
